<!--
    -  Copyright (c) 2018-2025, haohanwork.com All rights reserved.
  -->
<template>
  <div class="execution">
    <!--添加tab切换栏-->
    <template>
      <!-- <el-tabs v-model="activeName" @tab-click="handleClick" class="tabContent"> -->
        <!-- <el-tab-pane label="订单详情" name="orderDetail"> -->
          <!--切换订单详情显示的内容-->

          <div class="crumbs">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item><router-link to="/order_con/salesOrder">销售订单</router-link></el-breadcrumb-item>
              <el-breadcrumb-item>编辑销售单</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <basic-container>
            <h2 class="io-goods-detail">
              基础信息
            </h2>
            <el-form ref="customerForm"
                :model="customerOrder"
                label-width="120px"
                label-position="right">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="业务员:">
                            <el-select 
                              filterable
                              remote 
                              :remote-method="remoteStaffList" 
                              v-model="customerOrder.employeeId" 
                              placeholder="请选择">
                                <el-option v-for="item in teamList" :key="item.id" :label="item.name" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="客户名称:">
                            <select-customer-form 
                            :customerObj="{customerName: customerOrder.customerName, customerSn: customerOrder.customerSn}"
                            @changeCustomer="handleSelectCustomer"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="交货日期:">
                            <el-date-picker
                                class="fill-width"
                                :editable="false"
                                v-model="customerOrder.deliveryDate"
                                type="date"
                                placeholder="选择日期"
                                value-format="yyyy-MM-dd">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="销售单类型:">
                            <el-select
                                v-model="customerOrder.salesType"
                                placeholder="请选择">
                                <el-option key="1" label="代客下单" value="1">
                                </el-option>
                            <el-option key="2" label="自主下单" value="2">
                            </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="收货地址:">
                            <el-select
                                class="fill-width"
                                v-model="customerOrder.customerAddressId"
                                placeholder="请选择">
                                <el-option
                                    v-for="item in addressList"
                                    :key="item.id"
                                    :label="item.address"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="备注:">
                            <el-input
                                class="fill-width"
                                type="textarea"
                                v-model="customerOrder.remarks"
                                placeholder="">
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="8">
                        <el-form-item label="其它金额:">
                            <el-input-number class="fill-width" v-model="customerOrder.otherAmount" style="float: left" placeholder="请输入" :precision="2" @change="countPrice"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="商品合计金额:">
                            <el-input-number class="fill-width" :disabled="true" v-model="customerOrder.goodsTotalAmount" style="float: left" placeholder="请输入" :precision="2" @change="countPrice"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="总计金额:">
                            <el-input-number class="fill-width" v-model="customerOrder.totalAmount" style="float: left" placeholder="请输入" :precision="2" @change="countCouponAmount"></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="8">
                        <el-form-item label="优惠金额:">
                            <el-input-number class="fill-width" :disabled="true" v-model="customerOrder.couponAmount" style="float: left" placeholder="请输入" :precision="2"></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
                
                <el-row>
                    <el-form-item>
                        <el-button type="primary" @click="resetForm">重置</el-button>
                    </el-form-item>
                </el-row>
            </el-form>
            
          </basic-container>
          <basic-container>
            <h2 class="io-goods-detail">
              销售订单商品清单
            </h2>
            <template>
              <h4 class="title">普通商品列表</h4>
              <goods-record :disableRecord="true" :type="1" :customerId="customerOrder.customerSn" v-on:addGoods="addGoods" v-on:goodsSubmit="goodsSubmit" />
              <goods-table :type="1" :goodsTable="tableData" :disabled="disabled" @change="changeTable"/>

              <h4 class="title m-t">赠品列表</h4>
              <goods-record :disableRecord="true" :type="3" :customerId="customerOrder.customerSn" v-on:addGoods="addGoods" v-on:goodsSubmit="goodsSubmit" />
              <goods-table :type="3" :goodsTable="giftData" :disabled="disabled"/>

              <h4 class="title m-t">促销品列表</h4>
              <goods-record :disableRecord="true" :type="2" :customerId="customerOrder.customerSn" v-on:addGoods="addGoods" v-on:goodsSubmit="goodsSubmit" />
              <goods-table :type="2" :goodsTable="promotionData" :disabled="disabled" @change="changeTable"/>
             
            </template>
          </basic-container>
          <basic-container>
            <template>
              <div class="return-btn">
                <el-button type="primary" @click="save">保存</el-button>
                <el-button type="primary" plain @click="close">返回</el-button>
              </div>
            </template>
          </basic-container>
          <el-dialog title="选择商品" :visible.sync="dialogVisible">
            <goods-list @select="onSelectGoods"></goods-list>
          </el-dialog>
     
    </template>
  </div>
</template>
<!-- 采购退货 -->
<script>
  import { getDetail, editDetail }from '@/api/crm/salesorder';
  import { getModelList } from '@/api/goods/goodsmodel';
  import { mapGetters } from 'vuex';
  import Util from '@/util/pds/utils';
  import {fetchDict} from '@/util/util';
  let cookieUtil = new Util();
  import goodsList from '../customerOrder/components/goodsList.vue'
  import Request from './../request.js'
  import {getStore, setStore} from "@/util/store";
  import {
    fetchList as teamList,
  } from '@/api/crm/marketemployee'
  import {
    fetchList as address,
  } from '@/api/crm/customeraddress' //地址
  import goodsTable from '../customerOrder/components/goodsTable.vue';
  import goodsRecord from '../customerOrder/components/goodsRecord.vue';
  import selectCustomerForm from '@/components/crm/select_customer_form';
  import { getGoodsList, getGoodsModelList } from '@/api/goods/goods';
  export default {
    name: 'addpurchaseback',
    data() {
      return {
        request: new Request(),
        activeName: 'orderDetail',
        disabled: false,
        tableData: [],
        promotionData: [],
        customerOrder: this.customerOrderInfo(),
        sales_type:[],
        dialogVisible:false,
        selectedRowIndex:0,
        currentPage: 1,
        pageSize: 15,
        purchaseOrder: {
          methodType: 2,
          purchaseOrderType:2,
          reviewType: 2,
          buyFinalTime:'',
          needBuyNum: '',
          expensepre: '',
          expenseName: '',
          remark: ''
        },
        loading: false,
        selectGoods: {
          goodsName: '',
          loading: '',
          goodsList: [],
          goodsId: '',
          goodsModelList: []
        },
        teamList:[],
        addressList:[],
        sales_type:[],
        giftData:[]
      }
    },
    created(){
      fetchDict('scm_sales_type', this.sales_type);
      // this.init();
      this.fetchBuyerList()
    },
    components: {
      goodsList,
      goodsTable,
      goodsRecord,
      selectCustomerForm,
    },
    computed: {
      ...mapGetters(['tagWel', 'tagList', 'tag', 'website']),
      tagLen() {
        return this.tagList.length || 0
      }
    },
    beforeRouteEnter(to, from, next) {
    next(vm => vm.init(vm.$route.query.res.salesOrderSn));
  },
    methods:{
      async modelChange(row, index, type) {
        // 大于1时不重新请求接口
        if(row.goodsModelList > 1) return;
        const params = {
          shopId: getStore({name: "shopId"}),
          goodsId: row.id,
          current: 1,
          size: 1000
        }
        this.loading = true;
        const res = await getModelList(params);
        this.loading = false;
        const data = res.data.records;
        data.map(item => {
          item['goodsModelId'] = item.id;
          item['modelName'] = item.modelName;
          return item;
        })
        switch(type) {
        case 1:
          this.tableData[index].goodsModelList = data;
          break;
        case 2:
          this.promotionData[index].goodsModelList = data;
          break;
        case 3:
          this.giftData[index].goodsModelList = data;
          break;
        default:
          break;
        }
      },
      async handleSelectCustomer(customerObj) {
          if(this.customerOrder.customerSn === customerObj.customerSn) return;
          this.$set(this.customerOrder, 'customerAddressId', '');
          this.$set(this.customerOrder, 'customerSn', customerObj.customerSn);
          this.$set(this.customerOrder, 'customerName', customerObj.customerName);
          this.changeAddress(customerObj.customerSn);
      },
      // 计算优惠价格
      countCouponAmount() {
          let couponAmount = this.getTotalAmount() - this.customerOrder.totalAmount;
          this.$set(this.customerOrder, 'couponAmount', couponAmount);
      },
      resetForm() {
          this.disabled = true;
          this.customerOrder = this.customerOrderInfo();
      },
      changeTable(data, type) {
          switch(type) {
          case 1:
              this.tableData = data;
              break;
          case 2:
              this.promotionData = data;
              break;
          case 3:
              this.giftData = data;
              break;
          default:
              break;
          }
          this.countPrice();
      },
      addGoods(type) {
          switch(type) {
          case 1:
              this.tableData.push(this.orderListInfo()[0]);
              break;
          case 2:
              this.promotionData.push(this.orderListInfo()[0]);
              break;
          case 3:
              this.giftData.push(this.orderListInfo()[0]);
          default:
              break;
          }
      },
      async goodsSubmit(goodsText, type) {
          if(!goodsText) return this.$message.warning("请填写订单内容");
          let regex = /[\u3400-\u4DB5\u4E00-\u9FEA\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29\u{20000}-\u{2A6D6}\u{2A700}-\u{2B734}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}]+[0-9]+[\u3400-\u4DB5\u4E00-\u9FEA\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29\u{20000}-\u{2A6D6}\u{2A700}-\u{2B734}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}]/ug;
          let goodsList = goodsText.match(regex);
          if(!goodsList) return this.$message.warning("请填写订单内容");
          let regexName = /[\u3400-\u4DB5\u4E00-\u9FEA\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29\u{20000}-\u{2A6D6}\u{2A700}-\u{2B734}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}]+/u;
          let regexNum = /[0-9]+/;
          // 新增商品加入采购列表
          goodsList.forEach(async item =>{
              let name = item.match(regexName);
              let num = item.match(regexNum);
              if(name && num){
                  name = name[0];
                  num = num[0];
                  let info = {
                      goodsId: '',
                      goodsImg: '',
                      goodsName : name,
                      goodsNum : num,
                      goodsModel: '',
                      purchasePrice: '',
                      buyPrice: '',
                      unit: '',
                      remarks: '',
                      loading: false,
                      goodsList: [],
                      goodsModelList: [],
                      salesGoodsType: type
                  }
                  let res = await this.getGoodsList({goodsName: name});
                  if(res.length > 0) {
                      info.goodsList = res;
                      info.goodsName = res[0].id;
                      info.goodsModelList = res[0].goodsModelList;
                      info.goodsId = res[0].goodsModelList[0].id;
                      info.buyPrice = res[0].goodsModelList[0].modelPrice;
                  } 
                  this.pushList(info, type);
                  this.countPrice();
              }
          });
      },
      async remoteStaffList(name) {
        let query = {};
        if(name) query.name = name;
        let res = await teamList(Object.assign(query, {current: 1, size: 50}));
        this.teamList = res.data.data.records;
      },
      fetchBuyerList() {
        teamList({current: 1, size: 1000}).then(response => {
          this.teamList = response.data.data.records
        })

      },

      async init(salesOrderSn){
        let params = {
          salesOrderSn:salesOrderSn
        }
        let response = await getDetail(params);
        this.customerOrder = response.data.data;
        this.customerOrder.customerAddressId = this.customerOrder.address;
        for(let i in this.customerOrder.detailList) {
          let item = this.customerOrder.detailList[i];
          item['goodsModelList'] = [{
            goodsModelId: item.goodsModelId,
            modelName: item.modelName,
          }];
          item['thumbUrl'] = item.goodsImg;
          item['modelUnit'] = item.unit;
          item['buyPrice'] = item.dealPrice;
          item['goodsId'] = item.goodsModelId;
          let res = await getGoodsModelList({shopId: getStore({name: "shopId"}), goodsId: item.id});
          item['goodsModelList'] = res.data.data.records;
          switch(item.salesGoodsType) {
          case '1':
            this.tableData.push(item);
            break;
          case '2':
            this.promotionData.push(item);
            break;
          case '3':
            this.giftData.push(item);
            break;
          default:
            break;
          }
        }
        this.countCouponAmount();
        address({current: 1, size: 1000,customerSn:this.customerOrder.customerSn}).then(response => {
          this.addressList = response.data.data.records
        })
      },
      save(){
        let order = this.customerOrder;
        if(order.customerAddressId===this.customerOrder.address) delete order.customerAddressId;
        let detailList = [];
        const saleList = [].concat(this.tableData).concat(this.promotionData).concat(this.giftData);
        saleList.map(item => {
          if(!item.goodsNum) return this.$message.warning("请输入数量");
          if(!item.buyPrice && item.salesGoodsType !== '3') return this.$message.warning("请输入价格");
          detailList.push({
            goodsModelId: item.goodsId,
            salesGoodsType: item.salesGoodsType,
            goodsNum: item.goodsNum,
            dealPrice: item.salesGoodsType === '3' ? 0 : item.buyPrice,
            remarks:item.remarks});
        })
        order.detailList = detailList;
        editDetail(order).then(res => {
          this.$message.success('编辑成功')
          let _this = this;
          setTimeout(function () {
            _this.close();
          },2000)
        })
      },
      handleClick(tab, event) {
        console.log(tab, event);
      },
      showGoodsDialog($event, index) {
        this.dialogVisible = true
        this.selectedRowIndex = index
      },
      onGoodsSelectChange(e, row) {
        if(e){
          let selectedGoods = row.goodsList.filter(item => item.id === e)[0]
          row.goodsModelList = selectedGoods.goodsModelList
          this.$set(row, 'goodsName', selectedGoods.goodsName)
          this.$set(row, 'thumbUrl', selectedGoods.thumbUrl)
        }else{
          // 清空选项时
          this.$set(row, 'goodsId', '');
          row.goodsId = '';
        }
      },
      onSelectGoods(goods) {
        this.dialogVisible = false;
        this.selectGoods = goods;
      },
      // 商品选择相关
      searchGoodsByName(row) {
        // 将row信息传入
        let _this = this;
        return function (searchValue) {
          if (searchValue !== '') {
            row.loading = true
            console.log('time', searchValue);
            let params = {
              goodsName: searchValue,
            }
            params.shopId = getStore({name: "shopId"})
            params.pageNo = _this.currentPage
            params.pageSize = _this.pageSize
            params.goodsName = searchValue
            _this.request.getGoodsList(params).then(res => {
              if (res.code == 200) {
                _this.$set(row, 'goodsList', res.ext.list);
                _this.$set(row, 'loading', false);
                _this.goodsList = res.ext.list
                _this.currentPage = res.ext.pageNo
                _this.totalCount = res.ext.count
              } else if (res.code == '983') {
                _this.goodsList = []
              } else {
                _this.$message.error('请求失败')
              }
            })
          }
        }
      },
      customerOrderInfo() {
          return {
            otherAmount: 0,
            couponAmount: 0,
            customerSn: '',
            salesType: '',
            employeeId: '',
            customerAddressId: '',
            totalAmount: 0,
            remarks: '',
            deliveryDate: this.tomorrow(),
          };
      },
      tomorrow() {
          return this.$utils.getDiffDate(1);
      },
      addSubmit(goods,type){
        if(goods.goodsId == ''){
          this.$message.error('请先选择商品')
          return false
        }
        var good = {
          goodsId:goods.goodsModelList[0].goodsId,
          goodsImg: goods.thumbUrl,
          goodsName: goods.goodsName,
          unit: goods.goodsModelList[0].modelUnit,
          marketPrice: goods.goodsModelList[0].modelPrice,
          modelName:goods.goodsModelList[0].modelName,
          goodsNum: 1,
          remarks: '',
          dealPrice:goods.marketPrice,
          goodsModelList: goods.goodsModelList,
          goodsModelId:goods.goodsModelList[0].id,
          salesGoodsType: type
        }
        switch(type) {
        case 1:
          this.tableData.push(good);
          break;
        case 2:
          this.promotionData.push(good);
          break;
        case 3:
          this.giftData.push(good);
        default:
          break;
        }
        this.countPrice();
      },
      delGood(index,type){
        switch(type) {
        case 1:
          this.tableData.splice(index,1);
          break;
        case 2:
          this.promotionData.splice(index,1);
          break;
        case 3:
          this.giftData.splice(index,1);
          break;
        default:
          break;
        }
        this.countPrice();
      },
      countPrice(){
        this.$set(this.customerOrder, 'totalAmount', this.getTotalAmount());
        this.countCouponAmount();
        // this.customerOrder.totalAmount = 0;
        // for(var i in this.tableData){
        //   this.customerOrder.totalAmount += this.tableData[i].goodsNum*this.tableData[i].dealPrice;
        // }
        // this.promotionData.map(item => {
        //   this.customerOrder.totalAmount += item.goodsNum * item.dealPrice;
        // })
        // this.customerOrder.totalAmount = this.customerOrder.totalAmount.toFixed(2);
      },
      getTotalAmount() {
          let totalAmount = 0;
          let tableData = [].concat(this.tableData).concat(this.promotionData);
          tableData.map(item => {
              totalAmount += parseFloat(item.goodsNum*item.buyPrice);
          })
          this.$set(this.customerOrder, 'goodsTotalAmount', totalAmount);
          totalAmount += this.customerOrder.otherAmount;
          return totalAmount;
      },
      orderListInfo(){
          return [{
            goodsModelId: '',
            salesGoodsType: '',
            goodsNum: '',
            buyPrice: '',
            remarks: '',
          }];
      },
      close(){
        var str_before = location.href.split('#')[1];
        let { tag, key } = this.findTag(str_before);
        this.$store.commit('DEL_TAG', tag);
        this.$router.go(-1);
      },
      findTag(value) {
        let tag, key
        this.tagList.map((item, index) => {
          if (item.value === value) {
            tag = item
            key = index
          }
        })
        return { tag: tag, key: key }
      }
    }
  }
</script>

<style lang="scss">
  .crumbs{
      margin: 20px 10px;
    }
  .io-goods-detail{
    margin-bottom: 10px;
  }
  .settle-accounts{
    text-align: right;
  }
  .basic-information {
    margin-top: 20px;
    font-weight: inherit;
  }
  .return-btn{
    height: 100px;
    width: 100%;
    text-align: center;
    line-height: 100px;
  }
  .tabContent{
    padding-left: 10px;
    .el-tabs__item{
      font-size: 20px;
    }
  }
</style>
